package me.chan.helper;

import me.chan.util.ReflectUtil;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * Created by JanGin on 2017/6/18.
 */
public class BeanHelper {

    public static final Map<Class<?>, Object> GLOBAL_BEANS_MAP = new HashMap<>();

    static {
        Set<Class<?>> classSet = ClassHelper.getBeanClassSet();
        for(Class<?> clazz : classSet) {
            Object obj = ReflectUtil.newInstance(clazz);
            GLOBAL_BEANS_MAP.put(clazz, obj);
        }
    }

    public static Map<Class<?>, Object> getGlobalBeansMap() {
        return GLOBAL_BEANS_MAP;
    }

    public static <T> T getBean(Class<T> clazz) {
        if (!GLOBAL_BEANS_MAP.containsKey(clazz)) {
            throw new RuntimeException("cannot get the entity by the given class:" + clazz);
        }
        return (T) GLOBAL_BEANS_MAP.get(clazz);
    }
}
